﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Hosting;
using System.IO;
using System.Reflection;

namespace Host
{
    class AssemblyResourceVirtualFile : VirtualFile
    {
        string path;

        public AssemblyResourceVirtualFile(string virtualPath)
            : base(virtualPath)
        {
            path = VirtualPathUtility.ToAppRelative(virtualPath);
        }

        public override System.IO.Stream Open()
        {
            string[] parts = path.Split('/');

            string assemblyName = parts[2];
            string resourceName = parts[3];

            assemblyName = Path.Combine(HttpRuntime.BinDirectory, assemblyName);

            //
            // Carrega a dll em memória
            //
            byte[] assemblyBytes = File.ReadAllBytes(assemblyName);
            Assembly assembly = Assembly.Load(assemblyBytes);

            if (assembly != null)
            {

                string[] resourceList = assembly.GetManifestResourceNames();

                //
                // Procura pelo resource em IgnoreCase
                //
                resourceName = Array.Find(resourceList,
                    delegate(string r)
                    {
                        return r.Equals(resourceName, StringComparison.InvariantCultureIgnoreCase);
                    });

                return assembly.GetManifestResourceStream(resourceName);
            }

            return null;

        }
    }
}